// import 'package:flutter/foundation.dart';

import 'package:flutter/material.dart';
import 'package:hm_pda_app/components/top_header.dart';
import 'package:hm_pda_app/config/http_request.dart';
import 'package:hm_pda_app/components/loading_overlay.dart';

class InventoryInquiry extends StatefulWidget {
  const InventoryInquiry({super.key});

  @override
  State<InventoryInquiry> createState() => _InventoryInquiryState();
}

enum TypeEnum { summaryBySKU, byBatchRef }

class _InventoryInquiryState extends State<InventoryInquiry> {
  TypeEnum typeView = TypeEnum.byBatchRef;
  bool isChecked = false;
  final _skuController = TextEditingController();
  final _focusNode = FocusNode();
  // 声明列表数据
  List<ListItem> listData = <ListItem>[];
  List dataList = [];
  List<SummaryBySkuItem> summaryBySkuList = <SummaryBySkuItem>[];
  SkuInfo? _skuInfo;
  // 按批次查询 /storage/imSkuStorageBatch/list
  void _queryByBatch(BuildContext context) async {
    try {
      if (_skuController.text.isEmpty) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('请输入仓库sku'), duration: Duration(seconds: 3)),
        );
        return;
      }
      LoadingOverlay.show(context);
      var response = await HttpUtil.post(
        '/storage/imSkuStorageBatch/list',
        data: {
          'skuCode': _skuController.text,
          'filterZeroStorageFlag': isChecked,
        },
      );

      setState(() {
        listData.clear();
        if (response.code == 200 && response.data != null) {
          if (response.data is Map<String, dynamic>) {
            final dataMap = response.data as Map<String, dynamic>;
            if (dataMap['rows'] is List) {
              for (var item in dataMap['rows']) {
                listData.add(ListItem.fromJson(item));
              }
              _skuInfo = SkuInfo.fromJson(dataMap['rows'][0]);
              dataList = listData;
            }
          }

          print('listData--$listData');
        } else {
          // 处理错误情况
          print('Error: ${response.message}');
        }
      });
    } catch (e) {
      print(e);
    } finally {
      LoadingOverlay.hide();
    }
  }

  // 按sku汇总查询 SummaryBySkuItem /storage/imSkuStorageSummary/admin/list
  void _queryBySku(BuildContext context) async {
    try {
      if (_skuController.text.isEmpty) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('请输入仓库sku'), duration: Duration(seconds: 3)),
        );
        return;
      }
      LoadingOverlay.show(context);
      var response = await HttpUtil.post(
        '/storage/imSkuStorageSummary/admin/list',
        data: {
          'skuCode': _skuController.text,
          'filterZeroStorageFlag': isChecked,
        },
      );

      setState(() {
        summaryBySkuList.clear();
        if (response.code == 200 && response.data != null) {
          if (response.data is Map<String, dynamic>) {
            final dataMap = response.data as Map<String, dynamic>;
            if (dataMap['rows'] is List) {
              for (var item in dataMap['rows']) {
                summaryBySkuList.add(SummaryBySkuItem.fromJson(item));
              }
              _skuInfo = SkuInfo.fromJson(dataMap['rows'][0]);
              dataList = summaryBySkuList;
            }
          }

          print('listData--$listData');
        } else {
          // 处理错误情况
          print('Error: ${response.message}');
        }
      });
    } catch (e) {
      print(e);
    } finally {
      LoadingOverlay.hide();
    }
  }

  // 重置
  void _resetForm() {
    setState(() {
      _skuController.clear();
      dataList.clear();
      isChecked = false;
      typeView = TypeEnum.byBatchRef;
      listData.clear();
      summaryBySkuList.clear();
      _skuInfo = SkuInfo(
        skuCode: '',
        skuPackagingLengthSize: '',
        skuPackagingWidthSize: '',
        skuPackagingHeightSize: '',
        pictureUrl: '',
        skuGrossWeight: '',
        skuSalesStatusName: '',
      );
    });
    _focusNode.requestFocus();
  }

  void _showImagePreview(BuildContext context, String imageUrl) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return Dialog(
          backgroundColor: Colors.transparent,
          child: Stack(
            children: [
              Center(
                child: InteractiveViewer(
                  panEnabled: true, // 允许拖拽
                  boundaryMargin: EdgeInsets.all(20),
                  minScale: 0.1,
                  maxScale: 6.0,
                  child: SizedBox(
                    width: MediaQuery.of(context).size.width * 0.9,
                    child: Image.network(
                      imageUrl,
                      fit: BoxFit.contain,
                      errorBuilder: (context, error, stackTrace) {
                        return Container(
                          padding: EdgeInsets.all(20),
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Icon(Icons.error, size: 50, color: Colors.white),
                              SizedBox(height: 10),
                              Text(
                                '图片加载失败',
                                style: TextStyle(color: Colors.white),
                              ),
                            ],
                          ),
                        );
                      },
                    ),
                  ),
                ),
              ),
              Positioned(
                top: 40,
                right: 20,
                child: GestureDetector(
                  onTap: () => Navigator.of(context).pop(),
                  child: Container(
                    width: 40,
                    height: 40,
                    decoration: BoxDecoration(
                      color: Colors.black54,
                      shape: BoxShape.circle,
                    ),
                    child: Icon(Icons.close, color: Colors.white, size: 24),
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  @override
  void initState() {
    super.initState();
    _skuInfo = SkuInfo(
      skuCode: '',
      skuPackagingLengthSize: '',
      skuPackagingWidthSize: '',
      skuPackagingHeightSize: '',
      pictureUrl: '',
      skuGrossWeight: '',
      skuSalesStatusName: '',
    );
    _focusNode.requestFocus();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      //appBar: AppBar(title: const Text("移库")),
      appBar: const TopHeader(title: '库存查询'),
      endDrawer: const CustomDrawer(),
      resizeToAvoidBottomInset: false,
      body: SingleChildScrollView(
        padding: EdgeInsets.all(1),
        child: Column(
          children: [
            dataList.isEmpty
                ? Row(
                    children: [
                      Expanded(
                        child: Align(
                          alignment: Alignment.center,
                          child: SegmentedButton<TypeEnum>(
                            segments: const <ButtonSegment<TypeEnum>>[
                              ButtonSegment<TypeEnum>(
                                value: TypeEnum.byBatchRef,
                                label: Text('按批次明细查询'),
                              ),
                              ButtonSegment<TypeEnum>(
                                value: TypeEnum.summaryBySKU,
                                label: Text('按SKU汇总查询'),
                              ),
                            ],
                            selected: <TypeEnum>{typeView},
                            onSelectionChanged: (Set<TypeEnum> newSelection) {
                              setState(() {
                                // By default there is only a single segment that can be
                                // selected at one time, so its value is always the first
                                // item in the selected set.
                                typeView = newSelection.first;
                              });
                            },
                          ),
                        ),
                      ),
                    ],
                  )
                : SizedBox(width: 0),
            dataList.isEmpty
                ? Row(
                    children: [
                      Expanded(
                        flex: 1,
                        child: Align(
                          alignment: Alignment.topRight,
                          child: Checkbox(
                            tristate: false,
                            value: isChecked,
                            onChanged: (bool? value) {
                              setState(() {
                                isChecked = value ?? false;
                              });
                            },
                          ),
                        ),
                      ),

                      Expanded(
                        flex: 10,
                        child: Align(
                          alignment: Alignment.topLeft,
                          child: Text('是否显示0库存'),
                        ),
                      ),
                    ],
                  )
                : SizedBox(width: 0),
            dataList.isEmpty
                ? const Divider(
                    height: 2, // 容器总高度2像素
                    thickness: 1, // 分割线厚度5像素
                    indent: 0, // 左侧缩进20像素
                    endIndent: 0, // 右侧无缩进
                    color: Color.fromARGB(255, 109, 108, 108), // 黑色分割线
                  )
                : SizedBox(width: 0),
            dataList.isEmpty
                ? Row(
                    children: [
                      Expanded(
                        flex: 2,
                        child: Align(
                          alignment: Alignment.center,
                          child: _buildLabel('仓库SKU', isRequired: true),
                        ),
                      ),
                      Expanded(
                        flex: 8,
                        child: Align(
                          alignment: Alignment.centerLeft,
                          child: TextFormField(
                            controller: _skuController,
                            decoration: _buildInputDecoration(
                              hintText: '',
                              controller: _skuController,
                              suffixIcon:
                                  ValueListenableBuilder<TextEditingValue>(
                                    valueListenable: _skuController,
                                    builder: (context, value, child) {
                                      return value.text.isEmpty
                                          ? SizedBox.shrink()
                                          : IconButton(
                                              icon: Icon(Icons.clear, size: 20),
                                              onPressed: () {
                                                _skuController.clear();
                                              },
                                            );
                                    },
                                  ),
                            ),
                            focusNode: _focusNode,
                            onFieldSubmitted: (value) {
                              if (typeView == TypeEnum.byBatchRef) {
                                _queryByBatch(context);
                              } else {
                                _queryBySku(context);
                              }
                              print('回车执行');
                            },
                          ),
                        ),
                      ),
                    ],
                  )
                : SizedBox(width: 0),
            dataList.isEmpty
                ? SizedBox(width: 0)
                : SizedBox(child: _buildInfo()),

            // 添加库存列表展示
            dataList.isEmpty
                ? SizedBox(width: 0)
                : const Divider(
                    height: 2,
                    thickness: 1,
                    indent: 0,
                    endIndent: 0,
                    color: Color.fromARGB(255, 109, 108, 108),
                  ),

            dataList.isEmpty ? SizedBox(width: 0) : _buildList(),
          ],
        ),
      ),
      bottomNavigationBar: DecoratedBox(
        decoration: BoxDecoration(color: const Color.fromARGB(255, 77, 76, 76)),
        child: SizedBox(
          width: double.infinity,
          height: 50,
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16.0),
            child: Row(
              children: [
                Expanded(
                  child: SizedBox(
                    height: 40,
                    child: OutlinedButton(
                      onPressed: () {
                        // 取消操作，重置表单
                        _resetForm();
                      },
                      style: OutlinedButton.styleFrom(
                        foregroundColor: Colors.white,
                        backgroundColor: Colors.grey[600],
                        side: BorderSide.none,
                        textStyle: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w500,
                        ),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                        elevation: 1,
                      ),
                      child: const Text('重置'),
                    ),
                  ),
                ),
                const SizedBox(width: 12),

                Expanded(
                  child: SizedBox(
                    height: 40,
                    child: ElevatedButton(
                      onPressed: () {
                        _queryByBatch(context);
                      },
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.blue[600],
                        foregroundColor: Colors.white,
                        textStyle: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w600,
                        ),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                        elevation: 3,
                        // shadowColor: Colors.blue.withOpacity(0.3),
                      ),
                      child: const Text('查询'),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  // 列表数据展示-按批次明细
  Widget _buildList() {
    return typeView == TypeEnum.byBatchRef
        ? _batchSkuList()
        : _summaryBySkuList();
  }

  // 按批次展示
  Widget _batchSkuList() {
    if (dataList.isEmpty) {
      return SizedBox(
        height: 200,
        child: Center(
          child: Text(
            '暂无数据',
            style: TextStyle(fontSize: 16, color: Colors.grey[600]),
          ),
        ),
      );
    }

    return ListView.builder(
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      itemCount: listData.length,
      itemBuilder: (context, index) {
        final item = listData[index];
        return Card(
          margin: EdgeInsets.all(2),
          child: Padding(
            padding: EdgeInsets.all(8.0),
            child: Column(
              children: [
                Row(
                  children: [
                    Expanded(child: Text('采购单号:${item.purchaseOrderNo ?? ''}')),
                    Expanded(
                      child: Text('上架单号:${item.storagePutOnSaleNo ?? ''}'),
                    ),
                  ],
                ),
                Divider(
                  height: 1,
                  thickness: 1,
                  indent: 0,
                  endIndent: 0,
                  color: Color.fromARGB(255, 109, 108, 108),
                ),
                Row(
                  children: [
                    Expanded(child: Text('仓库:${item.warehouseName ?? ''}')),
                    Expanded(child: Text('库位:${item.locationCode ?? ''}')),
                  ],
                ),
                Row(
                  children: [
                    Expanded(
                      child: Text('首次库龄:${item.firstPutOnStorageAge ?? ''}'),
                    ),
                    Expanded(child: Text('首次上架:${item.firstPutOnTime ?? ''}')),
                  ],
                ),
                Row(
                  children: [
                    Expanded(
                      child: Text('最近库龄:${item.lastPutOnStorageAge ?? ''}'),
                    ),
                    Expanded(child: Text('最近上架:${item.lastPutOnTime ?? ''}')),
                  ],
                ),
                Row(
                  children: [
                    Expanded(
                      child: Text(
                        '采购在途:${item.purchaseInTransitQuantity ?? ''}',
                      ),
                    ),
                    Expanded(
                      child: Text(
                        '首次在途:${item.firstLegInTransitQuantity ?? ''}',
                      ),
                    ),
                  ],
                ),
                Row(
                  children: [
                    Expanded(
                      child: Text('待质检:${item.waitQualityCheckQuantity ?? ''}'),
                    ),
                    Expanded(
                      child: Text('待上架:${item.waitPutOnQuantity ?? ''}'),
                    ),
                  ],
                ),
                Row(
                  children: [
                    Expanded(
                      child: Text('可用库存:${item.availableStockQuantity ?? ''}'),
                    ),
                    Expanded(
                      child: Text('锁定库存:${item.lockedStockQuantity ?? ''}'),
                    ),
                  ],
                ),
                Row(
                  children: [
                    Expanded(
                      child: Text('次品库存:${item.defectiveQuantity ?? ''}'),
                    ),
                    Expanded(
                      child: Text('实际库存:${item.actualStockQuantity ?? ''}'),
                    ),
                  ],
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  // 按sku汇总
  Widget _summaryBySkuList() {
    if (dataList.isEmpty) {
      return SizedBox(
        height: 200,
        child: Center(
          child: Text(
            '暂无数据',
            style: TextStyle(fontSize: 16, color: Colors.grey[600]),
          ),
        ),
      );
    }

    return ListView.builder(
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      itemCount: summaryBySkuList.length,
      itemBuilder: (context, index) {
        final item = summaryBySkuList[index];
        return Card(
          margin: EdgeInsets.all(2),
          child: Padding(
            padding: EdgeInsets.all(8.0),
            child: Column(
              children: [
                Row(
                  children: [
                    Expanded(child: Text('仓库:${item.warehouseName ?? ''}')),
                    Expanded(
                      child: Text('实际在库:${item.actualStockQuantity ?? ''}'),
                    ),
                  ],
                ),
                Row(
                  children: [
                    Expanded(child: Text('成本单价:${item.costUnitPrice ?? ''}')),
                    Expanded(
                      child: Text('成本总金额:${item.costTotalAmount ?? ''}'),
                    ),
                  ],
                ),
                Row(
                  children: [
                    Expanded(
                      child: Text('采购计划:${item.purchasePlanQuantity ?? ''}'),
                    ),
                    Expanded(
                      child: Text(
                        '采购在途:${item.purchaseInTransitQuantity ?? ''}',
                      ),
                    ),
                  ],
                ),
                Row(
                  children: [
                    Expanded(
                      child: Text('头程计划:${item.firstLegPlanQuantity ?? ''}'),
                    ),
                    Expanded(
                      child: Text(
                        '头程在途:${item.firstLegInTransitQuantity ?? ''}',
                      ),
                    ),
                  ],
                ),
                Row(
                  children: [
                    Expanded(
                      child: Text('待质检:${item.waitQualityCheckQuantity ?? ''}'),
                    ),
                    Expanded(
                      child: Text('待上架:${item.waitPutOnQuantity ?? ''}'),
                    ),
                  ],
                ),
                Row(
                  children: [
                    Expanded(
                      child: Text('可用库存:${item.availableStockQuantity ?? ''}'),
                    ),
                    Expanded(
                      child: Text('锁定库存:${item.lockedStockQuantity ?? ''}'),
                    ),
                  ],
                ),
                Row(
                  children: [
                    Expanded(
                      child: Text(
                        '可售库存/天数:${item.sellableQuantity ?? ''}/${item.sellableDays ?? ''}',
                      ),
                    ),
                    Expanded(
                      child: Text(
                        '缺货数/天数:${item.outOfStockQuantity ?? ''}/${item.outOfStockDays ?? ''}',
                      ),
                    ),
                  ],
                ),
                Row(
                  children: [
                    Expanded(
                      child: Text('不良品:${item.defectiveQuantity ?? ''}'),
                    ),
                  ],
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  // sku信息
  Widget _buildInfo() {
    return SizedBox(
      child: Row(
        children: [
          Expanded(
            flex: 2,
            child: Align(
              alignment: Alignment.centerLeft,
              child:
                  _skuInfo?.pictureUrl != null &&
                      _skuInfo!.pictureUrl!.isNotEmpty
                  ? GestureDetector(
                      onTap: () {
                        _showImagePreview(context, _skuInfo!.pictureUrl!);
                      },
                      child: Image(
                        image: NetworkImage(_skuInfo!.pictureUrl!),
                        width: 100,
                        height: 100,
                        errorBuilder: (context, error, stackTrace) {
                          return Container(
                            width: 100,
                            height: 100,
                            color: Colors.grey[200],
                            child: Icon(
                              Icons.image_not_supported,
                              size: 50,
                              color: Colors.grey[400],
                            ),
                          );
                        },
                      ),
                    )
                  : Container(
                      width: 100,
                      height: 100,
                      color: Colors.grey[200],
                      child: Icon(
                        Icons.image,
                        size: 50,
                        color: Colors.grey[400],
                      ),
                    ),
            ),
          ),
          SizedBox(width: 1),
          Expanded(
            flex: 4,
            child: Align(
              alignment: Alignment.centerLeft,
              child: Column(
                children: [
                  Row(
                    children: [
                      Expanded(
                        flex: 1,
                        child: Align(
                          alignment: Alignment.centerLeft,
                          child: Text('SKU编码:${_skuInfo?.skuCode}'),
                        ),
                      ),
                    ],
                  ),
                  Row(
                    children: [
                      Expanded(
                        flex: 1,
                        child: Align(
                          alignment: Alignment.centerLeft,
                          child: Text(
                            '尺寸:${_skuInfo?.skuPackagingLengthSize ?? ''}x${_skuInfo?.skuPackagingWidthSize ?? ''}x${_skuInfo?.skuPackagingHeightSize ?? ''}cm',
                          ),
                        ),
                      ),
                    ],
                  ),
                  Row(
                    children: [
                      Expanded(
                        flex: 1,
                        child: Align(
                          alignment: Alignment.centerLeft,
                          child: Text('重量:${_skuInfo?.skuGrossWeight ?? ''}kg'),
                        ),
                      ),
                    ],
                  ),
                  Row(
                    children: [
                      Expanded(
                        flex: 1,
                        child: Align(
                          alignment: Alignment.centerLeft,
                          child: Text(
                            '状态:${_skuInfo?.skuSalesStatusName ?? '未知'}',
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 构建标签文本
  Widget _buildLabel(String text, {bool isRequired = false}) {
    return SizedBox(
      // width: 200,
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 2),
        child: Text(
          text,
          style: TextStyle(
            fontWeight: FontWeight.w500,
            fontSize: 16,
            color: isRequired ? Colors.red : Colors.grey[700],
          ),
        ),
      ),
    );
  }

  // 构建输入框装饰
  InputDecoration _buildInputDecoration({
    required String hintText,
    required TextEditingController controller,
    Widget? suffixIcon,
  }) {
    print('controller ${controller.text}');
    return InputDecoration(
      hintText: hintText,
      contentPadding: EdgeInsets.zero, // 设置上下左右内边距都为0
      // prefixIcon: Icon(prefixIcon, color: Colors.grey[600]),
      suffixIcon: suffixIcon,
      hintStyle: TextStyle(color: Colors.grey[500]),
      // isDense: true 属性用于减少输入框的垂直高度，使其更紧凑
      // 当设置为 true 时，会减少内边距，让输入框看起来更小更密集
      // 适用于需要节省空间或创建更紧凑布局的场景
      // isDense: true,
      filled: true,
      fillColor: Colors.grey[50],

      // suffixIcon: controller.text.isNotEmpty
      //             ? IconButton(
      //                 icon: Icon(Icons.clear, size: 20),
      //                 onPressed: () {
      //                   controller.clear();
      //                   // 需要通知父组件状态更新
      //                   if (mounted) {
      //                     setState(() {});
      //                   }
      //                 },
      //               )
      //             : null,
      border: OutlineInputBorder(
        borderRadius: BorderRadius.circular(8),
        borderSide: BorderSide(color: Colors.grey[300]!),
      ),
      enabledBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(8),
        borderSide: BorderSide(color: Colors.grey[300]!),
      ),
      focusedBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(8),
        borderSide: BorderSide(color: Colors.blue, width: 2),
      ),
      errorBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(8),
        borderSide: BorderSide(color: Colors.red),
      ),
      focusedErrorBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(8),
        borderSide: BorderSide(color: Colors.red, width: 2),
      ),
    );
  }
}

// 列表数据结构
class ListItem {
  final String? purchaseOrderNo;
  final String? storagePutOnSaleNo;
  final String? warehouseName;
  final String? locationCode;
  final String? firstPutOnStorageAge;
  final String? lastPutOnStorageAge;
  final String? firstPutOnTime;
  final String? lastPutOnTime;
  final String? purchaseInTransitQuantity;
  final String? firstLegInTransitQuantity;
  final String? waitQualityCheckQuantity;
  final String? waitPutOnQuantity;
  final String? availableStockQuantity;
  final String? lockedStockQuantity;
  final String? defectiveQuantity;
  final String? actualStockQuantity;
  ListItem({
    this.purchaseOrderNo,
    this.storagePutOnSaleNo,
    this.warehouseName,
    this.locationCode,
    this.firstPutOnStorageAge,
    this.lastPutOnStorageAge,
    this.firstPutOnTime,
    this.lastPutOnTime,
    this.purchaseInTransitQuantity,
    this.firstLegInTransitQuantity,
    this.waitQualityCheckQuantity,
    this.waitPutOnQuantity,
    this.availableStockQuantity,
    this.lockedStockQuantity,
    this.defectiveQuantity,
    this.actualStockQuantity,
  });
  factory ListItem.fromJson(Map<String, dynamic> json) {
    return ListItem(
      purchaseOrderNo: json['purchaseOrderNo']?.toString() ?? '',
      storagePutOnSaleNo: json['storagePutOnSaleNo']?.toString() ?? '',
      warehouseName: json['warehouseName']?.toString() ?? '',
      locationCode: json['locationCode']?.toString() ?? '',
      firstPutOnStorageAge: json['firstPutOnStorageAge']?.toString(),
      lastPutOnStorageAge: json['lastPutOnStorageAge']?.toString(),
      firstPutOnTime: json['firstPutOnTime']?.toString(),
      lastPutOnTime: json['lastPutOnTime']?.toString(),
      purchaseInTransitQuantity:
          json['purchaseInTransitQuantity']?.toString() ?? '0',
      firstLegInTransitQuantity:
          json['firstLegInTransitQuantity']?.toString() ?? '0',
      waitQualityCheckQuantity:
          json['waitQualityCheckQuantity']?.toString() ?? '0',
      waitPutOnQuantity: json['waitPutOnQuantity']?.toString() ?? '0',
      availableStockQuantity: json['availableStockQuantity']?.toString() ?? '0',
      lockedStockQuantity: json['lockedStockQuantity']?.toString() ?? '0',
      defectiveQuantity: json['defectiveQuantity']?.toString() ?? '0',
      actualStockQuantity: json['actualStockQuantity']?.toString() ?? '0',
    );
  }
}

// 按sku汇总
class SummaryBySkuItem {
  final String? warehouseName;
  final String? actualStockQuantity;
  final String? costUnitPrice;
  final String? costTotalAmount;
  final String? purchasePlanQuantity;
  final String? purchaseInTransitQuantity;
  final String? firstLegPlanQuantity;
  final String? firstLegInTransitQuantity;
  final String? waitQualityCheckQuantity;
  final String? waitPutOnQuantity;

  final String? availableStockQuantity;
  final String? lockedStockQuantity;
  final String? sellableQuantity;
  final String? sellableDays;
  final String? outOfStockQuantity;
  final String? outOfStockDays;
  final String? defectiveQuantity;
  SummaryBySkuItem({
    this.warehouseName,
    this.actualStockQuantity,
    this.costUnitPrice,
    this.costTotalAmount,
    this.purchasePlanQuantity,
    this.purchaseInTransitQuantity,
    this.firstLegPlanQuantity,
    this.firstLegInTransitQuantity,
    this.waitQualityCheckQuantity,
    this.waitPutOnQuantity,
    this.availableStockQuantity,
    this.lockedStockQuantity,
    this.sellableQuantity,
    this.sellableDays,
    this.outOfStockQuantity,
    this.outOfStockDays,
    this.defectiveQuantity,
  });
  factory SummaryBySkuItem.fromJson(Map<String, dynamic> json) {
    return SummaryBySkuItem(
      warehouseName: json['warehouseName']?.toString() ?? '',
      actualStockQuantity: json['actualStockQuantity']?.toString() ?? '',
      costUnitPrice: json['costUnitPrice']?.toString() ?? '',
      costTotalAmount: json['costTotalAmount']?.toString() ?? '',
      purchasePlanQuantity: json['purchasePlanQuantity']?.toString() ?? '',
      purchaseInTransitQuantity:
          json['purchaseInTransitQuantity']?.toString() ?? '',
      firstLegPlanQuantity: json['firstLegPlanQuantity']?.toString() ?? '',
      firstLegInTransitQuantity:
          json['firstLegInTransitQuantity']?.toString() ?? '',
      waitQualityCheckQuantity:
          json['waitQualityCheckQuantity']?.toString() ?? '',
      waitPutOnQuantity: json['waitPutOnQuantity']?.toString() ?? '',
      availableStockQuantity: json['availableStockQuantity']?.toString() ?? '',
      lockedStockQuantity: json['lockedStockQuantity']?.toString() ?? '',
      sellableQuantity: json['sellableQuantity']?.toString() ?? '',
      sellableDays: json['sellableDays']?.toString() ?? '',
      outOfStockQuantity: json['outOfStockQuantity']?.toString() ?? '',
      outOfStockDays: json['outOfStockDays']?.toString() ?? '',
      defectiveQuantity: json['defectiveQuantity']?.toString() ?? '',
    );
  }
}

// sku信息
class SkuInfo {
  final String? skuCode;
  final String? skuPackagingLengthSize;
  final String? skuPackagingWidthSize;
  final String? skuPackagingHeightSize;
  final String? pictureUrl;

  final String? skuGrossWeight;
  final String? skuSalesStatusName;
  SkuInfo({
    required this.skuCode,
    this.skuPackagingLengthSize,
    this.skuPackagingWidthSize,
    this.skuPackagingHeightSize,
    this.skuGrossWeight,
    this.skuSalesStatusName,
    this.pictureUrl,
  });
  factory SkuInfo.fromJson(Map<String, dynamic> json) {
    return SkuInfo(
      skuCode: json['skuCode']?.toString() ?? '',
      skuPackagingLengthSize: json['skuPackagingLengthSize']?.toString(),
      skuPackagingWidthSize: json['skuPackagingWidthSize']?.toString(),
      skuPackagingHeightSize: json['skuPackagingHeightSize']?.toString(),
      skuGrossWeight: json['skuGrossWeight']?.toString(),
      skuSalesStatusName: json['skuSalesStatusName']?.toString(),
      pictureUrl: json['pictureUrl']?.toString(),
    );
  }
}
